from PIL import Image, ImageDraw, ImageFont
import textwrap


def get_font_render_size(text, font_path, font_size):
    """
    :param text: 文字
    :param font_path: 字体路径
    :param font_size: 字体大小
    :return: tuple 宽高
    """
    canvas = Image.new('RGB', (2048, 2048))
    ImageDraw.Draw(canvas).text((0, 0),
                                text, font=ImageFont.truetype(font_path, font_size))
    bbox = canvas.getbbox()
    return bbox[2] - bbox[0], bbox[3] - bbox[1]


def main(text, logo_path="../static/templateSource/54/man/man_1.jpg", save_path="原文.jpg",
         font_path="fonts/msyhl.ttc", font_size=60, space_length=15,
         bg_height=64, max_line_length=14):
    # 将文本分割成多行
    lines = textwrap.wrap(text, width=max_line_length)

    # 计算文字渲染后的长度
    max_text_width = 0
    total_text_height = 0
    for line in lines:
        text_width, text_height = get_font_render_size(line, font_path, font_size)
        max_text_width = max(max_text_width, text_width)
        total_text_height += text_height

    # 定义背景宽度
    bg_width = max_text_width + space_length
    bg_height = total_text_height + space_length  # 调整背景高度以适应多行文本

    # 生成背景

    bg_img = Image.new(mode='RGB', size=(bg_width + 50, bg_height), color="#F5F5F5")

    # 读取头像文件，并绘制头像到背景图片

    # 绘制气泡
    ## 1. 绘制圆角矩形
    x, y, w, h, r = space_length, 0, max_text_width + space_length * 1.5+15, bg_height, space_length
    fill_color = "#0000FF"
    draw_object = ImageDraw.Draw(bg_img)

    draw_object.ellipse((x, y, x + r, y + r), fill=fill_color)
    draw_object.ellipse((x + w - r, y, x + w, y + r), fill=fill_color)
    draw_object.ellipse((x, y + h - r, x + r, y + h), fill=fill_color)
    draw_object.ellipse((x + w - r, y + h - r, x + w, y + h), fill=fill_color)

    draw_object.rectangle((x + r / 2, y, x + w - (r / 2), y + h), fill=fill_color)
    draw_object.rectangle((x, y + r / 2, x + w, y + h - (r / 2)), fill=fill_color)

    ## 2. 绘制三角形 （对话的哪个尖尖） 26.0  16.0  36.0

    if len(lines) > 1:
        # 多行文本的尖尖坐标
        draw_object.polygon([
            (space_length / 2, 26.0),
            (space_length, 16.0),
            (space_length, 36.0),
        ], fill="#0000FF")
    else:
        # 单行文本的尖尖坐标
        draw_object.polygon([
            (space_length / 2, bg_height / 2),
            (space_length, bg_height / 2 - space_length / 2),
            (space_length, bg_height / 2 + space_length / 2),
        ], fill="#0000FF")
    ## 3. 绘制字体
    y_text = (bg_height - total_text_height) // 2-15
    for line in lines:
        draw_object.text((space_length + 15, y_text),
                         line, fill=0, font=ImageFont.truetype(font_path, font_size))
        _, text_height = get_font_render_size(line, font_path, font_size)
        y_text += text_height

    bg_img.save(save_path)


if __name__ == "__main__":
    main("更改此处文字即可更改此处")  # 更改此处文字即可。
